﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Configuration.Provider;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Web.Security;
using Application.Services;
using Microsoft.Practices.Unity;
using Domaine.Entity;
namespace DistributedServices.MembershipModule.Providers
{
   public class LMSMembershipProvider:System.Web.Security.MembershipProvider
    {

        
        #region Const

        private const int PASSWORD_SIZE = 14;
        private const int SALT_SIZE_IN_BYTES = 16;

        #endregion


        #region Members

        IAppMembershipService appMembershipService;

        private bool _EnablePasswordReset;
        private bool _EnablePasswordRetrieval;
        private int _MaxInvalidPasswordAttempts;
        private int _MinRequiredNonAlphanumericCharacters;
        private int _MinRequiredPasswordLength;
        private int _PasswordAttemptWindow;
        private System.Web.Security.MembershipPasswordFormat _PasswordFormat;
        private string _PasswordStrengthRegularExpression;
        private bool _RequiresQuestionAndAnswer;
        private bool _RequiresUniqueEmail;
        private string _connectionString;
        private System.Web.Configuration.MembershipPasswordCompatibilityMode _LegacyPasswordCompatibilityMode;
        private string s_HashAlgorithm;
        #endregion



        #region Properties
        public override string ApplicationName { get; set; }
        public override bool EnablePasswordReset { get { return _EnablePasswordReset; } }
        public override bool EnablePasswordRetrieval { get { return _EnablePasswordRetrieval; } }
        public override int MaxInvalidPasswordAttempts { get { return _MaxInvalidPasswordAttempts; } }
        public override int MinRequiredNonAlphanumericCharacters { get { return _MinRequiredNonAlphanumericCharacters; } }
        public override int MinRequiredPasswordLength { get { return _MinRequiredPasswordLength; } }
        public override int PasswordAttemptWindow { get { return _PasswordAttemptWindow; } }
        public override System.Web.Security.MembershipPasswordFormat PasswordFormat { get { return _PasswordFormat; } }
        public override string PasswordStrengthRegularExpression { get { return _PasswordStrengthRegularExpression; } }
        public override bool RequiresQuestionAndAnswer { get { return _RequiresQuestionAndAnswer; } }
        public override bool RequiresUniqueEmail { get { return _RequiresUniqueEmail; } }

        public string ConnectionString { get { return _connectionString; } }
        public string TablePrefix { get; private set; }
        public string TableSchema { get; private set; }
        #endregion

        #region Ctor
        public LMSMembershipProvider()
        {
            appMembershipService = DistributedServices.MembershipModule.InstanceProvider.Container.Current.Resolve<IAppMembershipService>();
                
        }
        #endregion
        #region public Methods

        #region Initialize

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
                throw new ArgumentNullException("config");
            if (String.IsNullOrEmpty(name))
                name = "LMSMembershipProvider";
            if (config["description"] == null)
            {
                config.Remove("description");
                config.Add("description", "Ado.net Entity Framework Membership Provider");
            }
            base.Initialize(name, config);

            TablePrefix = GetStringValue(config, "tablePrefix", "");
            TableSchema = GetStringValue(config, "tableSchema", "");
            _EnablePasswordRetrieval = GetBooleanValue(config, "enablePasswordRetrieval", false);
            _EnablePasswordReset = GetBooleanValue(config, "enablePasswordReset", true);
            _RequiresQuestionAndAnswer = GetBooleanValue(config, "requiresQuestionAndAnswer", true);
            _RequiresUniqueEmail = GetBooleanValue(config, "requiresUniqueEmail", true);
            _MaxInvalidPasswordAttempts = GetIntValue(config, "maxInvalidPasswordAttempts", 5, false, 0);
            _PasswordAttemptWindow = GetIntValue(config, "passwordAttemptWindow", 10, false, 0);
            _MinRequiredPasswordLength = GetIntValue(config, "minRequiredPasswordLength", 7, false, 128);
            _MinRequiredNonAlphanumericCharacters = GetIntValue(config, "minRequiredNonalphanumericCharacters", 1, true, 128);

            _PasswordStrengthRegularExpression = config["passwordStrengthRegularExpression"];
            if (_PasswordStrengthRegularExpression != null)
            {
                _PasswordStrengthRegularExpression = _PasswordStrengthRegularExpression.Trim();
                if (_PasswordStrengthRegularExpression.Length != 0)
                {
                    try
                    {
                        Regex regex = new Regex(_PasswordStrengthRegularExpression);
                    }
                    catch (ArgumentException e)
                    {
                        throw new ProviderException(e.Message, e);
                    }
                }
            }
            else
            {
                _PasswordStrengthRegularExpression = string.Empty;
            }
            if (_MinRequiredNonAlphanumericCharacters > _MinRequiredPasswordLength)
                throw new ProviderException("MinRequiredNonalphanumericCharacters_can_not_be_more_than_MinRequiredPasswordLength");

            string temp = config["connectionStringName"];
            if (temp == null || temp.Length < 1)
                throw new ProviderException("Connection_name_not_specified");
            if (System.Configuration.ConfigurationManager.ConnectionStrings[temp] == null)
                throw new ProviderException("Connection_not_found");
            _connectionString = temp;

            ApplicationName = GetStringValue(config, "applicationName", "/");
            if (ApplicationName.Length > 256)
                throw new ProviderException("Provider_application_name_too_long");

            string strTemp = GetStringValue(config, "passwordFormat", "Hashed");
            switch (strTemp)
            {
                case "Clear": _PasswordFormat = MembershipPasswordFormat.Clear; break;
                case "Encrypted": _PasswordFormat = MembershipPasswordFormat.Encrypted; break;
                case "Hashed": _PasswordFormat = MembershipPasswordFormat.Hashed; break;
                default:
                    throw new ProviderException("Provider_bad_password_format");
            }

            if (PasswordFormat == MembershipPasswordFormat.Hashed && EnablePasswordRetrieval)
                throw new ProviderException("Provider_can_not_retrieve_hashed_password");

            string passwordCompactMode = config["passwordCompatMode"];
            if (!string.IsNullOrEmpty(passwordCompactMode))
            {
                this._LegacyPasswordCompatibilityMode = (MembershipPasswordCompatibilityMode)Enum.Parse(typeof(MembershipPasswordCompatibilityMode), passwordCompactMode);
            }

        }

        #endregion

        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {

            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);
            if (member == null) return false;

            var passwordFormat = member.PasswordFormat;
            var passwordSalt = member.PasswordSalt;

            var check = CheckPassword(member,oldPassword, passwordFormat, passwordSalt, false, false, true);

            if (!check)
            {
                this.appMembershipService.UpdateMemmber(member);
                return false;
            }

            if (this.PasswordFormat != passwordFormat)
            {
                passwordFormat = PasswordFormat;
                passwordSalt = GenerateSalt();
            }
            member.Password = EncodePassword(newPassword, passwordFormat, passwordSalt);
            member.LastPasswordChangedDate = DateTime.UtcNow;
            member.FailedPasswordAnswerAttemptCount = 0;
            member.FailedPasswordAttemptCount = 0;
            this.appMembershipService.UpdateMemmber(member);
            return true;
        }





        public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
        {
            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);
            if (member == null) return false;

            var passwordFormat = member.PasswordFormat;
            var passwordSalt = member.PasswordSalt;
            var check = CheckPassword(member, password, passwordFormat, passwordSalt, false, false, true);
            if (!check)
            {
                this.appMembershipService.UpdateMemmber(member);
                return false;
            }
            member.PasswordQuestion = newPasswordQuestion;
            member.PasswordAnswer = EncodePassword(newPasswordAnswer.ToLower(), passwordFormat, passwordSalt);
            this.appMembershipService.UpdateMemmber(member);
            return true;
        }


        public override System.Web.Security.MembershipUser CreateUser(string username, string password,
                                                                      string email, string passwordQuestion, string passwordAnswer,
                                                                      bool isApproved, object providerUserKey,
                                                                      out System.Web.Security.MembershipCreateStatus status)
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                status = MembershipCreateStatus.InvalidUserName;
                return null;
            }

            Guid providerKey = Guid.NewGuid();
            if (providerUserKey != null)
            {
                try
                {
                    var newkey = Guid.Parse(providerUserKey.ToString());
                    if (newkey != Guid.Empty )
                    {
                        providerKey = newkey;
                    }

                }
                catch (Exception)
                {
                    status = MembershipCreateStatus.InvalidProviderUserKey;
                    return null;
                }

            }

            if (!IsValidEmail(email))
            {
                status = MembershipCreateStatus.InvalidEmail;
                return null;
            }


            int count = 0;
            for (int i = 0; i < password.Length; i++)
                if (!char.IsLetterOrDigit(password, i))
                    count++;

            if (count < this.MinRequiredNonAlphanumericCharacters)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            if (this.PasswordStrengthRegularExpression.Length > 0)
            {
                if (!Regex.IsMatch(password, PasswordStrengthRegularExpression))
                {
                    status = MembershipCreateStatus.InvalidPassword;
                    return null;
                }
            }


            var passArgs = new ValidatePasswordEventArgs(username, password, true);
            OnValidatingPassword(passArgs);

            if (passArgs.Cancel)
            {
                status = MembershipCreateStatus.InvalidPassword;
                return null;
            }

            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);

            if (member != null && member.User!=null)
            {
                status = MembershipCreateStatus.DuplicateUserName;
                return null;
            }

            if (providerUserKey != null)
            {
                var userKey = this.appMembershipService.GetMemmberByUserID(providerKey);

                if (userKey != null)
                {
                    status = MembershipCreateStatus.DuplicateProviderUserKey;
                    return null;
                }
            }
             member = this.appMembershipService.GetMemmberByUserEmail( email);
             
            if (member != null )
            {
                status = MembershipCreateStatus.DuplicateEmail;
                return null;
            }

            var app = this.appMembershipService.GetAspApplication();
            if (app == null)
            {
                app = new Domaine.Entity.AspApplication()
                {
                    ApplicationID = Guid.NewGuid(),
                    ApplicationName = "/",
                };
                this.appMembershipService.AddAspApplication(app);
            }
            var passwordSalt = GenerateSalt();
            var encodedPassword = EncodePassword(password, PasswordFormat, passwordSalt);
            string question = "";
            string answer = "";
            if (passwordAnswer != null)
            {
                var encodedAnswer = EncodeAnswerPassword(passwordAnswer, PasswordFormat, passwordSalt);
                question = passwordQuestion;
                answer = encodedAnswer;
            }
            var now = DateTime.UtcNow;
            Domaine.Entity.Membership newMember = new Domaine.Entity.Membership()
            {
                User = new Domaine.Entity.User()
               {
                   UserID = providerKey,
                   Application = app,
                   ApplicationID = app.ApplicationID,
                   UserName = username,
                   LastActivityDate = now,
                   IsAnonymous = false
               },
                UserID = providerKey,
                ApplicationID = app.ApplicationID,
                Email = email,
                IsApproved = isApproved,
                PasswordFormat = PasswordFormat,
                PasswordSalt = passwordSalt,
                Password = encodedPassword,
                PasswordQuestion = question,
                PasswordAnswer=answer,
                CreateDate = now,
                LastLockoutDate = now,
                LastLoginDate = now,
                LastPasswordChangedDate = now,
                FailedPasswordAttemptWindowStart = now,
                FailedPasswordAnswerAttemptWindowStart = now,
                IsLockedOut = false,
                Comment = ""
            };
            this.appMembershipService.AddMember (newMember);
            status = MembershipCreateStatus.Success;
            return newMember.ToMembershipUser(this.Name);
        }


        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);
            if (member == null) return false;

            try
            {
                this.appMembershipService.RemoveMember(member);

                if (deleteAllRelatedData)
                {
                     
                }

                return true;
            }
            catch
            {
                return false;
            }
        }



        public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException("FindUsersByEmail");
        }

        public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
        {
            throw new NotImplementedException("FindUsersByName");
        }

        public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
        {
          
            var members = this.appMembershipService.GetPagedMembers (pageIndex, pageSize );
            if (members == null || !members.Any())
            {
                totalRecords = 0;
                return null;
            }
            MembershipUserCollection collection = new MembershipUserCollection();
            foreach (var member in members)
            {

                collection.Add(member.ToMembershipUser(this.Name));
                     
            }
            totalRecords = members.Count();
            return collection;
        }

        public override int GetNumberOfUsersOnline()
        {
            throw new NotImplementedException("GetNumberOfUsersOnline");
        }

        public override string GetPassword(string username, string answer)
        {
            if (!EnablePasswordRetrieval)
                throw new NotSupportedException("Membership_PasswordRetrieval_not_supported");
            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);
            if (member == null) return null;

            var passwordFormat = member.PasswordFormat;
            var passwordSalt = member.PasswordSalt;
            var dbAnswer = member.PasswordAnswer;
            if (!CheckAnswerPassword(member,  answer, passwordFormat, passwordSalt, true))
            {
                this.appMembershipService.UpdateMemmber(member);
                return null;
            }
            member.FailedPasswordAnswerAttemptCount = 0;
            member.FailedPasswordAttemptCount = 0;
            this.appMembershipService.UpdateMemmber(member);
            return UnEncodePassword(member.Password, passwordFormat);
        }



        public override System.Web.Security.MembershipUser GetUser(string username, bool userIsOnline)
        {
            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);
            if (member == null) return null;
            if (userIsOnline)
            {
                member.User.LastActivityDate = DateTime.UtcNow;
                this.appMembershipService.UpdateMemmber(member);
            }

            return member.ToMembershipUser(this.Name);

        }
        public override System.Web.Security.MembershipUser GetUser(object providerUserKey, bool userIsOnline)
        {
            Guid providerKey = Guid.Parse(providerUserKey.ToString());
            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserID(providerKey);
            if (member == null) return null;

            if (userIsOnline)
            {
                member.User.LastActivityDate = DateTime.UtcNow;
                this.appMembershipService.UpdateMemmber(member);
            }

            return member.ToMembershipUser(this.Name);
        }




        public override string GetUserNameByEmail(string email)
        {
            throw new NotImplementedException("GetUserNameByEmail");
        }



        public override string ResetPassword(string username, string answer)
        {
            throw new NotImplementedException();
        }

        public override bool UnlockUser(string userName)
        {
            throw new NotImplementedException("UnlockUser");
        }

        public override void UpdateUser(MembershipUser user)
        {
            throw new NotImplementedException("UpdateUser");
        }

        public override bool ValidateUser(string username, string password)
        {
            Domaine.Entity.Membership member = this.appMembershipService.GetMemmberByUserName(username);
            if (member == null) return false;

            var passwordFormat = member.PasswordFormat;
            var passwordSalt = member.PasswordSalt;

            var check = CheckPassword(member, password, passwordFormat, passwordSalt, true, true, true);
            member.User.LastActivityDate = DateTime.UtcNow;
            this.appMembershipService.UpdateMemmber(member);

            return check;
        }



        #endregion


        #region local Methods

        string GetStringValue(NameValueCollection config, string Key, string Default)
        {
            string sValue = config[Key];
            if (sValue == null)
                return Default;

            return sValue;
        }


        public bool GetBooleanValue(NameValueCollection config, string Key, bool Default)
        {
            string sValue = config[Key];
            if (sValue == null)
                return Default;

            bool result;
            if (bool.TryParse(sValue, out result))
                return result;
            else
                throw new ProviderException("Value_must_be_boolean");

        }



        int GetIntValue(NameValueCollection config, string valueName, int defaultValue, bool zeroAllowed, int maxValueAllowed)
        {
            string sValue = config[valueName];

            if (sValue == null)
                return defaultValue;

            int iValue;
            if (!Int32.TryParse(sValue, out iValue))
            {
                if (zeroAllowed)
                    throw new ProviderException("Value_must_be_non_negative_integer");

                throw new System.Configuration.Provider.ProviderException("Value_must_be_positive_integer");
            }

            if (zeroAllowed && iValue < 0)
                throw new ProviderException("Value_must_be_non_negative_integer");

            if (!zeroAllowed && iValue <= 0)
                throw new ProviderException("Value_must_be_positive_integer");

            if (maxValueAllowed > 0 && iValue > maxValueAllowed)
                throw new ProviderException("Value_too_big");

            return iValue;
        }


        internal bool CheckPassword(Domaine.Entity.Membership member,  string Password, MembershipPasswordFormat Format, string Salt, bool UpdateActivity, bool UpdateLogin, bool LockIsPossible)
        {

            if (member == null) return false;
            if (member.IsLockedOut) return false;

            var Hashed = EncodePassword(Password, Format, Salt);
            var storedPassword = member.Password;
            if (Hashed.Equals(storedPassword, StringComparison.OrdinalIgnoreCase))
            {
                if (UpdateActivity)
                    member.User.LastActivityDate = DateTime.UtcNow;

                if (UpdateLogin)
                    member.LastLoginDate = DateTime.UtcNow;

                if (LockIsPossible)
                {
                    member.FailedPasswordAttemptCount = 0;
                    member.FailedPasswordAttemptWindowStart = new DateTime(1800, 1, 1);
                }

                return true;
            }
            else
            {
                if (LockIsPossible)
                {
                    var faileds = member.FailedPasswordAttemptCount + 1;
                    var failedOn = member.FailedPasswordAttemptWindowStart;

                    var utc = DateTime.UtcNow;
                    if (failedOn.AddMinutes(this.PasswordAttemptWindow) >= utc)
                        member.FailedPasswordAttemptCount = 1;
                    else
                        member.FailedPasswordAttemptCount = faileds;

                    member.FailedPasswordAttemptWindowStart = utc;
                    if (faileds >= this.MaxInvalidPasswordAttempts)
                    {
                        member.IsLockedOut = true;
                    }
                }

                return false;
            }
        }


        internal string EncodePassword(string pass, MembershipPasswordFormat passwordFormat, string salt)
        {
            if (passwordFormat == MembershipPasswordFormat.Clear)
            {
                return pass;
            }
            byte[] bytes = Encoding.Unicode.GetBytes(pass);
            byte[] src = Convert.FromBase64String(salt);
            byte[] inArray = null;
            if (passwordFormat == MembershipPasswordFormat.Hashed)
            {
                HashAlgorithm hashAlgorithm = this.GetHashAlgorithm();
                if (hashAlgorithm is KeyedHashAlgorithm)
                {
                    KeyedHashAlgorithm algorithm2 = (KeyedHashAlgorithm)hashAlgorithm;
                    if (algorithm2.Key.Length == src.Length)
                    {
                        algorithm2.Key = src;
                    }
                    else if (algorithm2.Key.Length < src.Length)
                    {
                        byte[] dst = new byte[algorithm2.Key.Length];
                        Buffer.BlockCopy(src, 0, dst, 0, dst.Length);
                        algorithm2.Key = dst;
                    }
                    else
                    {
                        int num2;
                        byte[] buffer5 = new byte[algorithm2.Key.Length];
                        for (int i = 0; i < buffer5.Length; i += num2)
                        {
                            num2 = Math.Min(src.Length, buffer5.Length - i);
                            Buffer.BlockCopy(src, 0, buffer5, i, num2);
                        }
                        algorithm2.Key = buffer5;
                    }
                    inArray = algorithm2.ComputeHash(bytes);
                }
                else
                {
                    byte[] buffer6 = new byte[src.Length + bytes.Length];
                    Buffer.BlockCopy(src, 0, buffer6, 0, src.Length);
                    Buffer.BlockCopy(bytes, 0, buffer6, src.Length, bytes.Length);
                    inArray = hashAlgorithm.ComputeHash(buffer6);
                }
            }
            else
            {
                byte[] buffer7 = new byte[src.Length + bytes.Length];
                Buffer.BlockCopy(src, 0, buffer7, 0, src.Length);
                Buffer.BlockCopy(bytes, 0, buffer7, src.Length, bytes.Length);
                inArray = this.EncryptPassword(buffer7, _LegacyPasswordCompatibilityMode);
            }
            return Convert.ToBase64String(inArray);
        }

        private HashAlgorithm GetHashAlgorithm()
        {
            if (this.s_HashAlgorithm != null)
            {
                return HashAlgorithm.Create(this.s_HashAlgorithm);
            }
            string hashAlgorithmType = "SHA1";

            if (((this._LegacyPasswordCompatibilityMode == MembershipPasswordCompatibilityMode.Framework20)) && (hashAlgorithmType != "MD5"))
            {
                hashAlgorithmType = System.Web.Security.Membership.HashAlgorithmType;
            }
            HashAlgorithm algorithm = HashAlgorithm.Create(hashAlgorithmType);
            if (algorithm == null)
            {
                throw new ConfigurationErrorsException("Invalid_hash_algorithm_type");
            }
            this.s_HashAlgorithm = hashAlgorithmType;
            return algorithm;
        }

        internal string GenerateSalt()
        {
            byte[] buf = new byte[SALT_SIZE_IN_BYTES];
            (new RNGCryptoServiceProvider()).GetBytes(buf);
            return Convert.ToBase64String(buf);
        }

        internal string EncodeAnswerPassword(string pass, MembershipPasswordFormat passwordFormat, string salt)
        {
            return EncodePassword(pass.ToLower().Trim(), passwordFormat, salt);
        }

        internal bool CheckAnswerPassword(Domaine.Entity.Membership member, string Answer,
                                                       MembershipPasswordFormat Format,
                                                       string Salt, bool LockIsPossible)
        {
            if (member.IsLockedOut) return false;

            var Hashed = EncodePassword(Answer.ToLower(), Format, Salt);
            if (Hashed.Equals(member.PasswordAnswer, StringComparison.OrdinalIgnoreCase))
            {
                if (LockIsPossible)
                {
                    member.FailedPasswordAnswerAttemptCount = 0;
                    member.FailedPasswordAnswerAttemptWindowStart = new DateTime(1800, 1, 1);
                }

                return true;
            }
            else
            {
                if (LockIsPossible)
                {
                    var faileds = member.FailedPasswordAnswerAttemptCount + 1;
                    var failedOn = member.FailedPasswordAnswerAttemptWindowStart;

                    var utc = DateTime.UtcNow;
                    if (failedOn.AddMinutes(this.PasswordAttemptWindow) >= utc)
                        member.FailedPasswordAnswerAttemptCount = 1;
                    else
                        member.FailedPasswordAnswerAttemptCount = faileds;

                    member.FailedPasswordAnswerAttemptWindowStart = utc;
                    if (this.MaxInvalidPasswordAttempts >= faileds)
                    {
                        member.IsLockedOut = true;
                    }
                }

                return false;
            }
        }

        internal string UnEncodePassword(string pass, MembershipPasswordFormat passwordFormat)
        {
            switch (passwordFormat)
            {
                case MembershipPasswordFormat.Clear:
                    return pass;
                case MembershipPasswordFormat.Hashed:
                    throw new ProviderException("Provider_can_not_decode_hashed_password");
                default:
                    byte[] bIn = Convert.FromBase64String(pass);
                    byte[] bRet = DecryptPassword(bIn);
                    if (bRet == null)
                        return null;
                    return Encoding.Unicode.GetString(bRet, SALT_SIZE_IN_BYTES, bRet.Length - SALT_SIZE_IN_BYTES);
            }
        }

        #region Validators

       
          
            
        

        protected virtual bool IsValidEmail(string email)
        {
            try
            {
                var ValidEmail = new System.Net.Mail.MailAddress(email);
                return true;
            }
            catch
            {
                return false;
            }
             
        }

        #endregion
        #endregion

    }
}
